﻿using ApiLib.Common.Attributes;
using ApiLib.Utils;
using SqlSugar;

namespace ApiLib.Models;

/// <summary>
/// 基础数据库类：包含创建人、创建时间、修改人、修改时间
/// </summary>
public abstract class BaseEntity
{
    /// <summary>
    /// 创建人 
    ///</summary>
    [SugarColumn(ColumnName = "create_user", IsOnlyIgnoreUpdate = true, ColumnDataType = "nvarchar(10)",
        IsNullable = true)]
    [Excel(IsIgnore = true)]
    public virtual string CreateUser { get; set; } = "";

    /// <summary>
    /// 创建人 
    ///</summary>
    [SugarColumn(IsIgnore = true)]
    [Excel("创建人")]
    public virtual string CreateUserName { get; set; } = "";

    /// <summary>
    /// 创建时间 
    ///</summary>
    [SugarColumn(ColumnName = "create_time", IsOnlyIgnoreUpdate = true, InsertServerTime = true, IsNullable = true)]
    [Excel("创建时间")]
    public virtual DateTime CreateTime { get; set; }

    /// <summary>
    /// 更新人 
    ///</summary>
    [SugarColumn(ColumnName = "update_user", IsOnlyIgnoreInsert = true, ColumnDataType = "nvarchar(10)",
        IsNullable = true)]
    [Excel(IsIgnore = true)]
    public virtual string UpdateUser { get; set; } = "";

    /// <summary>
    /// 更新人 
    ///</summary>
    [SugarColumn(IsIgnore = true)]
    [Excel("修改人")]
    public virtual string UpdateUserName { get; set; } = "";

    /// <summary>
    /// 更新时间 
    ///</summary>
    [SugarColumn(ColumnName = "update_time", IsOnlyIgnoreInsert = true, UpdateServerTime = true, IsNullable = true)]
    [Excel("修改时间")]
    public virtual DateTime? UpdateTime { get; set; }

    /// <summary>
    /// 初始化创建人
    /// </summary>
    public void InitCreateUser()
    {
        CreateUser = WebUtil.GetSid();
        CreateTime = CommonUtil.LocalDateTime();
    }

    /// <summary>
    /// 初始化修改人
    /// </summary>
    public void InitUpdateUser()
    {
        UpdateUser = WebUtil.GetSid();
        UpdateTime = CommonUtil.LocalDateTime();
    }
}

/// <summary>
/// 基础数据库类：包含自增id
/// </summary>
public abstract class BaseEntityIdentity : BaseEntity
{
    /// <summary>
    ///  
    ///</summary>
    [SugarColumn(ColumnName = "id", IsPrimaryKey = true, IsIdentity = true)]
    [Excel(IsIgnore = true)]
    public virtual int Id { get; set; }

    /// <summary>
    /// 初始化创建人或者修改人
    /// </summary>
    public void InitSaveUser()
    {
        if (Id == 0)
        {
            InitCreateUser();
        }
        else
        {
            InitUpdateUser();
        }
    }
}